#!/usr/bin/env python
#coding:utf-8
"""
  Author:  程勇 --<>
  Purpose: 动脑学院18节作业
  Created: 2018/3/8
"""

import os
import queue
import threading
import multiprocessing
import time

r_list = range(1,11)
#计算1-99999的总和
def sum_range():
    return sum(list(range(1,100000)))

'''1.计算range(1,99999)的总和,采取三种方式,第一:重复10次计算总时间;
 第二:开启十个子线程去计算;第三:开启十个进程去计算,然后对比耗时'''
def step_end():
    start_time = time.time()
    
    for i in r_list:
        sum_range()
        
    end_time = time.time()    
    print('批处理执行时间为:{}'.format(end_time - start_time))
 
def process_handle():
    start_time = time.time()
    
    pool = multiprocessing.Pool(10)
    for i in r_list:
        pool.apply_async(sum_range,args=())
    pool.close()
    pool.join()
    
    end_time = time.time()
    print('多进程进程池执行时间为:{}'.format(end_time - start_time))

def thread_handle():
    start_time = time.time()
    
    t_list = []
    for i in r_list:
        t_list.append(threading.Thread(target=sum_range,args=()))
    
    for t in t_list:
        t.start()
        t.join()
        
    end_time = time.time()
    print('多线程执行时间为:{}'.format(end_time - start_time))
     
'''2.将第一题计算十次改为使用线程池去计算,线程池线程个数由你自己电脑cpu逻辑核数决定'''   
from concurrent.futures import ThreadPoolExecutor,ProcessPoolExecutor
def second_thread_pool():
    start_time = time.time()
    
    with ThreadPoolExecutor(max_workers=multiprocessing.cpu_count()) as executor:
        future_sum = [executor.submit(sum_range) for i in r_list]
        
    end_time = time.time()
    print('线程池执行时间为:{}'.format(end_time - start_time))
    

if __name__ == '__main__':
    
    print('10次计算1-10000的总和，三种方式所用的时间')
    step_end()
    time.sleep(1)
    process_handle()
    time.sleep(1)
    thread_handle()
    time.sleep(1)
    
    print('线程池计算1-10000的总和，所用的时间')
    second_thread_pool()